import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../../../providers/ApiPro.service';
import { NzModalService } from 'ng-zorro-antd';
import { ActivatedRoute, Router, RouterLink, RouterModule } from '@angular/router';
import { HybBigCustomerAddDto } from '../HuoMesstmp.model';

import {
    FormBuilder,
    FormGroup,
    FormControl,
    Validators
} from '@angular/forms';

@Component({
  selector: 'app-MessCusInfoDialog',
  templateUrl: './MessCusInfoDialog.component.html',
  styleUrls: ['./MessCusInfoDialog.component.scss']
})
export class MessCusInfoDialogComponent implements OnInit {
  public validateForm: FormGroup;
  public cusDto: HybBigCustomerAddDto = new HybBigCustomerAddDto();
  public token = {
     Authorization: null
   };
  public fileUrl = null;
  public ischeck: boolean = false;
  public isEdit: boolean = false;
  public submitFlg: boolean = true;
  public fileList = [];

    _submitForm() {
          this.validateForm.value.contractUrl = this.fileUrl;
      this.validateForm.value.signTime = this.apiService.formatDateTime2( this.validateForm.value.signTime);
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[ i ].markAsDirty();
        // if(this.validateForm.value[ i ] == null || this.validateForm.value[ i ] ==''){
        //   this.submitFlg = false;
        // }
      }

    console.log(this.validateForm);
    // this.createNew();
      if(this.validateForm.valid){
        if(this.validateForm.value.contractUrl){
        this.createNew();
                  
        }else{
          this.error("合同未上传")
        }
      }
      console.log(this.validateForm.value)
    }

  constructor(
    private fb: FormBuilder,
    private apiService: ApiService,
    private router: Router,
    private route: ActivatedRoute,
    private confirmServ: NzModalService
) { }

  ngOnInit() {
    this.getToken();
    this.getId();
  }

  initForm(){
     this.validateForm = this.fb.group({
      customerAccount  : [ null, [ Validators.required, this.phoneValidator ] ],
      companyName      : [ null, [ Validators.required ] ],
      customerMobile   : [ null, [ Validators.required, this.phoneValidator ] ],
      customerName     : [ null, [ Validators.required ] ],
      deposit          : [ null, [ Validators.required ] ],
      signTime         : [ null, [ Validators.required ] ],
      contractUrl      : [ null,],
      salesman         : [ null, [ Validators.required ] ],
      password         : [ null, [ Validators.required ] ],
    });
  }

  getId(){
     this.route.params.subscribe((params) => {
            if((params['id'])){
              this.load(params['id']);
              this.isEdit = true;
           }else{
             this.initForm();
           }
        });

  }

  getToken(){
    this.token.Authorization = "Bearer "+this.apiService.getLocalStroage();
  }

  load(id) {
    this.initForm();
    let url = "findbigcustomerdetail";
    let flie ={
    uid: -1,
    name: '合同',
    status: 'done',
    url: null,
    }
    this.apiService.get(url, { "bigCustomerId": id })
      .then(res => {
        this.validateForm = this.fb.group({
          bigCustomerId    : [ res.result.bigCustomerId ,],
          customerAccount  : [ res.result.customerAccount, [ Validators.required , this.phoneValidator] ],
          companyName      : [ res.result.companyName, [ Validators.required ] ],
          customerMobile   : [ res.result.customerMobile, [ Validators.required, this.phoneValidator ] ],
          customerName     : [ res.result.customerName, [ Validators.required ] ],
          deposit          : [ res.result.deposit, [ Validators.required ] ],
          signTime         : [ res.result.signTime, [ Validators.required ] ],
          contractUrl      : [ res.result.contractUrl, [ Validators.required ] ],
          salesman         : [ res.result.salesman, [ Validators.required ] ],
          password         : [ res.result.password, [ Validators.required ] ],
        });
        flie.url = res.result.contractUrl;
        this.fileUrl = res.result.contractUrl;
      })
    this.fileList.push(flie);
    this.ischeck = !this.ischeck;
  }


  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  consl(){
    console.log("上传图片")
  }


 handleChange(info): void {
   this.ischeck = !this.ischeck;
   if(this.ischeck){
     if(info.file.response){
      this.fileUrl = info.file.response.result;
     }
   }
  }

  createNew(){
    console.log(this.fileUrl);
    let url = "insert";
    let url2 = "update";
      if(this.isEdit){
        this.apiService.post(url2,this.validateForm.value)
           .then(res =>{
          console.log(res);
          if(res.result){
            this.success();          
          }else{
            this.error(res.errMsg);
          }
        })
        .catch(err =>{
          console.log(err);
          this.error(err.errMsg);
        })
      }else{
        this.apiService.post(url,this.validateForm.value)
        .then(res =>{
          console.log(res);
          if(res.result){
            this.success();          
          }else{
            this.error(res.errMsg);
          }
        })
        .catch(err =>{
          console.log(err);
          this.error(err.errMsg);
        })
      }
    
  }

  error(err) {
    this.confirmServ.error({
      title: '错误',
      content: err,
      okText:'返回'
    });
  }

  success(){
    let self = this;
      this.confirmServ.success({
      title: '成功',
      content: '大客户信息完善',
      okText:'返回',
      onOk() {
        self.router.navigateByUrl("layout/mess/cusinfo");
      },
    });
  }

  phoneValidator = (control: FormControl): { [s: string]: boolean } => {
    const pw_REGEXP = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!control.value) {
      return { required: true }
    } else if (!pw_REGEXP.test(control.value)) {
      return { error: true, customerMobile: true , customerAccount: true};
    }
  };

}
